<template>
  <div class="minPageCon">
      <div class="des">
          <p v-if="userType=='personal'">전문가가 도와주는</br>당신의 2번째 커리어,</br><b>지금 시작해볼까요?</b></p>
          <p v-else>기업에서 필요로하는</br>경력이 풍부한 인재,</br><b>지금 만나볼까요?</b></p>
          <img src="@images/login_bg.png" alt="">
      </div>
      <div class="box">
        <h1>로그인</h1>
        <el-tabs v-model="userType" @tab-click="userTypeChange">
            <el-tab-pane label="개인회원" name="personal"></el-tab-pane>
            <el-tab-pane label="기업회원" name="enterprise"></el-tab-pane>
        </el-tabs>
        <!-- <el-alert title="개인회원" type="error" :closable="false"></el-alert> -->
        <el-form class="loginFrm" :model="loginFrm" :rules="rules" ref="loginFrm">
            <el-form-item prop="email">
                <el-input placeholder="아이디(이메일)" v-model="loginFrm.email" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input type="password" placeholder="비밀번호" v-model="loginFrm.password" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item>
                <el-checkbox v-model="loginFrm.checked">아이디저장</el-checkbox>
                <div class="link">
                    <el-link :underline="false" @click="openPage('/forgotName')">아이디찾기</el-link>
                    <el-divider direction="vertical"></el-divider>
                    <el-link :underline="false" @click="openPage('/forgotPwd')">비밀번호찾기</el-link>
                </div>
            </el-form-item>
            <el-form-item>
                <el-button :loading="loading" type="primary" class="subBtn" @click="submitForm('loginFrm')">로그인</el-button>
                <el-button class="signBtn" @click="signUp()" plain>회원가입</el-button>
            </el-form-item>
        </el-form>
        <el-divider>or</el-divider>
        <div class="other">

          <a href="javascript:;" target="_self" class="type1">
            <!-- <naverLogin class="btn" v-if="naverParams.clientId"
              :client-id="naverParams.clientId"
              :callback-url="naverParams.callbackUrl"
              :is-popup="false"
              :callbackFunction="callbackNaver"
            /> -->
            <div class="btn" id="naverIdLogin"></div>
            <i></i>네이버로 로그인
          </a>
          <a href="javascript:;" target="_self" class="type2">
            <kakaoLogin class="btn" v-if="kakaoParams.apiKey"
              :api-key="kakaoParams.apiKey"
              image="kakao_login_btn_medium"
              :on-success='onSuccessKakao'
              :on-failure='onFailureKakao'
            />
            <i></i>카카오로 로그인
          </a>
          <!-- <a href="javascript:;" target="_self" class="type3">
            <GoogleLogin class="btn" :params="GoogleParams" :onSuccess="onSuccessGoogle" :onFailure="onFailureGoogle">
            </GoogleLogin>
            <i></i>구글로 로그인
          </a>
          <a href="javascript:;" target="_self" class="type4">
            <div class="btn" @click="handleFacebookLogin">
            </div>
              <i></i>페이스북 로그인
          </a> -->
        </div>
      </div>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex";
import { login, getUserInfo, thirdPartyLogin } from '@/api';
import { Local } from '@/utils'
import { setToken } from '@/utils/auth'
// import NaverLogin from 'vue-naver-login'
import KakaoLogin from 'vue-kakao-login'
import GoogleLogin from 'vue-google-login';
import facebookLogin from 'facebook-login';
export default {
  name: '',
  components: { KakaoLogin, GoogleLogin },
  props: [],
  data () {
    var validateEmail = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('아이디를 입력해 주세요.'));
      } else if (!value.match(/^[a-zA-Z0-9_-|.]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/)) {
        callback(new Error('정확한 이메일 주소를 입력하세요.'));
      } else {
        callback();
      }
    };
    return {
      naverParams: {
        clientId: 'CL6iLQtA6yL1kF6odclx',
        callbackUrl: 'https://workwiz.co.kr/login'
      },
      kakaoParams: {
        apiKey: 'badcfdcb5500bdd090ad94401916abac',
      },
      GoogleParams: {
        client_id: '68727679949-ttsj9um7gf4bb9r78k164oaqcr6i49pv.apps.googleusercontent.com',
        // ItyZHLNfM3mGwcBt69I2SCpG
        // client_id: '429484770917-ktj0hiebi92tp4p4233q632vvvle1efg.apps.googleusercontent.com',
      },
      userType: 'personal',
      loading: false,
      redirect: undefined,
      otherQuery: {},
      loginFrm: {
        email: '',
        password: '',
        member_type: 1,
        checked: false
      },
      rules: {
        email: [
          { required: true, validator: validateEmail, trigger: 'change' }
        ],
        password: [
          { required: true, message: '비밀번호를 입력해주십시오.', trigger: 'blur' }
        ],
      },
      otherLogin: {
        type: '',
        token: ''
      },
      naverLogin: null
    }
  },
  computed: {},
  created () {
    this.userType = this.$route.query.userType || 'personal';
    if (this.userType == 'enterprise') {
      this.loginFrm.member_type = 2;
      this.naverParams.callbackUrl = 'https://workwiz.co.kr/login?userType=enterprise'
    }
  },
  mounted () {
    let _this = this;
    try {
      _this.naverLogin = new naver.LoginWithNaverId({
        clientId: _this.naverParams.clientId,
        callbackUrl: _this.naverParams.callbackUrl,
        isPopup: false,
        loginButton: { color: "green", type: 3, height: 60 }
      });
      _this.naverLogin.init();
      window.addEventListener('load', function () {
        _this.naverLogin.getLoginStatus(function (status) {
          _this.callbackNaver(status)
        });
      });
    } catch (error) { }
  },
  methods: {
    ...mapActions(['setUserToken', 'setRole', 'setUserInfo']),
    userTypeChange (tab) {
      this.loginFrm.email = '';
      this.loginFrm.password = '';
      if (tab.name == 'enterprise') {
        this.loginFrm.member_type = 2
      } else {
        this.loginFrm.member_type = 1
      }
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid, error) => {
        if (valid) {
          this.loading = true;
          this.$store.dispatch('login', this.loginFrm)
            .then(() => {
              this.getUserInfo()
              this.loading = false
            })
            .catch(() => {
              this.loading = false
            })
        } else {
          return false;
        }
      });
    },
    async getUserInfo (type) {
      let res = await getUserInfo();
      if (res.code == 200) {
        let _type = 'personal'
        if (res.data.member_type == 2) {
          _type = 'enterprise'
        }
        this.setRole(_type);
        Local.set('ust', _type);
        this.setUserInfo(res.data)
        Local.set('userInfo', res.data)

        this.$store.dispatch('setAccessRoutes')
        this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
        // window.location.reload();
        if (type == 3) {
          this.$alert('로그인 성공하였습니다.', '알림', {
            confirmButtonText: '확인',
          })
        }
      } else {
        if (type == 3) {
          this.$alert('로그인 실패하였습니다.', '알림', {
            confirmButtonText: '확인',
          })
        }
      }
    },
    signUp () {
      if (this.userType == 'personal') {
        this.$router.push({ path: '/register' })
      } else {
        this.$router.push({ path: '/registerEnt' })
      }
    },
    openPage (_path) {
      this.$router.push({ path: _path, query: { userType: this.userType } })
    },
    getOtherQuery (query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    async thirdPartyLogin () {
      let res = await thirdPartyLogin({ type: this.otherLogin.type, token: this.otherLogin.token });
      if (res.code == 200) {
        this.setUserToken(res.data.token)
        setToken(res.data.token)
        this.getUserInfo(3)
      } else {
        Local.set('thirdData', res.data)
        let _path = '/register';
        if (this.userType == 'enterprise') {
          _path = '/registerEnt'
        }
        this.$alert('로그인 성공하였습니다. 다음을 눌러 회원가입을 완료해주세요.', '알림', {
          confirmButtonText: '다음',
          callback: action => {
            this.$router.push({ path: _path, query: { type: 'thirdLogin' } })
          }
        })
      }
    },
    callbackNaver (status) {
      if (status) {
        this.otherLogin.type = 'naver';
        this.otherLogin.token = this.naverLogin.accessToken.accessToken;
        this.thirdPartyLogin();
      } else {
        // this.$alert('로그인 실패하였습니다.', '알림', {
        //   confirmButtonText: '확인',
        // })
      }
    },
    onSuccessKakao (data) {
      this.otherLogin.type = 'kakao';
      this.otherLogin.token = data.access_token;
      this.thirdPartyLogin();
    },
    onFailureKakao (data) {

      // this.$alert('로그인 실패하였습니다.', '알림', {
      //   confirmButtonText: '확인',
      // })
    },
    onSuccessGoogle (data) {
      console.log('%c 🥫 googlewc.access_token: ', 'font-size:20px;background-color: #4b4b4b;color:#fff;', data.wc.access_token);
      console.log('%c 🥫 google: ', 'font-size:20px;background-color: #4b4b4b;color:#fff;', data);
      this.otherLogin.type = 'google';
      this.otherLogin.token = data.wc.access_token;
      this.thirdPartyLogin();
    },
    onFailureGoogle () {

    },
    handleFacebookLogin () {
      const api = facebookLogin({ appId: '367171817989340' });
      // to trigger the login flow
      api.login().then((response) => {
        this.otherLogin.type = 'facebook';
        this.otherLogin.token = response.authResponse.accessToken;
        this.thirdPartyLogin();
        console.log(response.authResponse.accessToken, 'Facebook')
        console.log(response, 'Facebook response')
      });
      // to check if the user is connected
      // api.getLoginStatus().then((response) => console.log(response));
      // // to indicate when the SDK is done loading
      // api.whenLoaded().then(() => console.log('loaded!'));
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query
        if (query) {
          query.userType ? (this.userType = query.userType) : (this.userType = 'personal')
          query.redirect && (this.redirect = query.redirect, this.otherQuery = this.getOtherQuery(query))
        }
      },
      immediate: true
    }
  }
}
</script>
<style lang="scss" scoped>
@import 'css/user.scss';
</style>
